package com.ferrlo.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ferrlo.model.Project;
import com.ferrlo.service.IProjectManager;


@Controller
public class KickoffController {
	
	@Resource(name="projectManager")
	private IProjectManager projectManager;


	@RequestMapping(value="/kickoff")
	public ModelAndView register(@RequestParam(value = "img", required = false) MultipartFile img,HttpServletRequest request) throws IOException{
		
		ModelAndView mv = new ModelAndView();
		mv.setViewName("kickoff-result");
		
		Project project = new Project();
		
		String ptitle = request.getParameter("ptitle");
		String pdescription = request.getParameter("pdescription");
		String starter = request.getParameter("starter");
		String plocation = request.getParameter("plocation");
		String sintroduction = request.getParameter("sintroduction");
		String pcontent = request.getParameter("content");
		
		
		System.out.println("ptitle "+ptitle+"pdesc: "+pdescription+"start "+starter+"ploc"+plocation+"sinto "+sintroduction+" pcontent "+pcontent);
		System.out.println("======= " + (img == null ? "kong " : "not null"));

		project.setPName(ptitle);
		project.setPIntroduce(pdescription);
		project.setPPlace(plocation);
		project.setPInformation(pcontent);
		project.setPStartTime(new Date());
		
		String basePath = request.getServletContext().getRealPath("/project");
		String fileName = ptitle+"-"+System.nanoTime()+".jpg";
		File file = new File(basePath,fileName);
		if(!file.getParentFile().exists())
			file.getParentFile().mkdirs();

		InputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			inputStream = img.getInputStream();
			 outputStream = new FileOutputStream(file);
			byte[] b = new byte[1024];
			int n = 0;
			while((n = inputStream.read(b)) != -1){
				outputStream.write(b, 0, n);
			}
			project.setPPhoto("/Ferrlo/project/"+fileName);
		} catch (IOException e1) {
			e1.printStackTrace();
		}finally{
			inputStream.close();
			outputStream.close();
		}
		
		try {
			projectManager.save(project);
			mv.addObject("message", "New Project Success.");
		} catch (Exception e) {
			e.printStackTrace();
			mv.addObject("message", "New Project Failed.");
		}
//		
//		File file = new File(request.getServletContext().getRealPath("/upload"));
//		if(!file.exists())
//			file.mkdir();

		return mv;
	}

}
